package cn.rkylin.oms.item.adapter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import cn.rkylin.core.utils.StringUtil;
import cn.rkylin.oms.common.base.AbstractAdapterFactory;
import cn.rkylin.oms.common.utils.DateUtil;
import cn.rkylin.oms.system.shop.service.IShopService;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import cn.rkylin.core.IDataBaseFactory;
import cn.rkylin.core.utils.SnoGerUtil;
import cn.rkylin.oms.item.domain.Item;
import cn.rkylin.oms.item.domain.Sku;
import cn.rkylin.oms.item.vo.ItemVO;

/**
 * 淘宝商品适配器
 *
 * @author jipengcheng
 * @version 1.0
 * @created 2017.02.13
 */
@Service("taoBaoItemAdapter")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class TaoBaoItemAdapter extends ItemAdapter {
    private static final Log logger = LogFactory.getLog(TaoBaoItemAdapter.class);

    @Resource(name = "redisTemplate")
    private RedisTemplate<Serializable, Serializable> redisTemplate;

    /**
     * 数据库访问对象
     */
    @Autowired
    private IDataBaseFactory dao;

    @Autowired
    private IShopService shopService;

    /**
     * 构造函数
     */
    public TaoBaoItemAdapter() {
    }

    /**
     * 下载平台商品
     *
     * @param shopId
     * @return 1成功，0失败
     */
    @Override
    public int downloadByItemCode(String shopId, Map<String, Object> paramMap) {
        try {
            List<Item> itemList = getItemVisitor().getItemListByItemCode(shopId, paramMap);
            if (itemList == null) {
                return 0;
            }
            saveData(shopId, itemList);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return 0;
        }
        return 1;
    }

    /**
     * 下载平台商品
     *
     * @param shopId
     * @return 1成功，0失败
     */
    @Override
    public int downloadByModifyTime(String shopId, Map<String, Object> paramMap) throws Exception {

        ShopVO shop = AbstractAdapterFactory.getShop(shopId);
        String dateTimeStart = "";
        String dateTimeEnd = "";

        // 这里重新设置开始时间和结束时间
        dateTimeStart = DateUtil.formatDate(shop.getJobEcItemLastUpdateTime());
        dateTimeEnd = DateUtil.getCurrentDateStr("yyyy-MM-dd HH:mm:ss");
        paramMap.put("startTime", dateTimeStart);
        paramMap.put("endTime", dateTimeEnd);

        List<Item> itemList = getItemVisitor().getItemListByModifyTime(shopId, paramMap);
        if (itemList == null) {
            return 0;
        }
        saveData(shopId, itemList);

        if (paramMap.containsKey("startTime")) {
            // 更新最后执行时间
            ShopVO shopUpdate = new ShopVO();
            shopUpdate.setShopId(shopId);
            shopUpdate.setJobEcItemLastUpdateTime(StringUtil.strToDateTime(dateTimeEnd));
            shopService.update(shopUpdate);
        }
        return 1;
    }

    /**
     * 下载平台商品
     *
     * @param shopId
     * @return 1成功，0失败
     */
    @Override
    public int downloadAll(String shopId) {
        try {
            List<Item> itemList = getItemVisitor().getItemListAll(shopId);
            if (itemList == null) {
                return 0;
            }
            saveData(shopId, itemList);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            return 0;
        }
        return 1;
    }

    /**
     * 自动同步店铺库存并上下架
     *
     * @param shopId
     * @return 错误消息
     * @throws Exception 异常
     */
    @Override
    public String autoSynchStock(String shopId) throws Exception {
        return getItemVisitor().autoSynchStock(shopId);
    }

    /**
     * 手动同步库存根据商品
     *
     * @param ecItemId
     * @return 错误消息
     * @throws Exception 异常
     */
    @Override
    public String manualSynchStockByItem(String ecItemId) throws Exception {
        return getItemVisitor().manualSynchStockByItem(ecItemId);
    }

    /**
     * 手动同步库存根据SKU
     *
     * @param ecSkuId
     * @return 错误消息
     * @throws Exception 异常
     */
    @Override
    public String manualSynchStockBySku(String ecSkuId) throws Exception {
        return getItemVisitor().manualSynchStockBySku(ecSkuId);
    }

    /**
     * 保存数据
     *
     * @param shopId
     * @param itemList
     * @throws Exception
     */
    private void saveData(String shopId, List<Item> itemList) throws Exception {

        Map<String, Object> execMap = new HashMap<String, Object>();

        // 把itemList保存到数据库中。
        for (Item item : itemList) {
            int tempItem = 0;
            // 检查平台商品是否存在
            ItemVO parameter = new ItemVO();
            parameter.setShopId(shopId);
            parameter.setEcItemCode(item.getEcItemCode());
            Item itemModel = (Item) dao.find("selectByItemCodeItem", parameter);

            // 缓存处理：如果没有缓存就重新算一下
            setShopProductsAmount(shopId, parameter);

            if (itemModel == null) {
                // 插入
                item.setEcItemId(SnoGerUtil.getUUID());
                tempItem = dao.insert("insertSelectiveItem", item);

                try {
                    redisTemplate.opsForValue().increment("shopProductAmount:" + shopId, 1);
                } catch (Exception ex) {
                    logger.error(ex.getMessage(), ex);
                } // over
            } else {
                // 更新
                item.setEcItemId(itemModel.getEcItemId());
                tempItem = dao.update("updateByItemCodeSelectiveItem", item);
            }
            // 执行成功
            if (tempItem > 0) {
                // 标记sku为删除
                execMap.put("ecItemCode", item.getEcItemCode());
                execMap.put("shopId", shopId);
                dao.update("deleteByItemCodeSku", execMap);
                execMap.clear();

                int iTemp = 0;
                // 轮询商品sku, 平台商品规格信息
                for (Sku sku : item.getSkuList()) {
                    // 检查sku是否存在
                    execMap.put("ecItemCode", sku.getEcItemCode());
                    execMap.put("ecSkuCode", sku.getEcSkuCode());
                    execMap.put("shopId", shopId);
                    Sku skuModel = (Sku) dao.find("selectByItemCodeAndSkuCodeSku", execMap);
                    execMap.clear();
                    if (skuModel == null) {
                        // 插入
                        sku.setEcSkuId(SnoGerUtil.getUUID());
                        sku.setEcItemId(item.getEcItemId());
                        dao.insert("insertSelectiveSku", sku);
                    } else {
                        // 更新
                        sku.setEcSkuId(skuModel.getEcSkuId());
                        sku.setEcItemId(item.getEcItemId());
                        sku.setDeleted("n");
                        dao.update("updateByItemCodeAndSkuCodeSelectiveSku", sku);

                        // 判断该平台商品是否关联系统商品
                        if ("y".equals(skuModel.getIsGroup())) {
                            iTemp++;
                        } else if ("n".equals(skuModel.getIsGroup()) && StringUtils.isNotBlank(skuModel.getSkuId())) {
                            iTemp++;
                        }

//                        if (StringUtils.isNotBlank(skuModel.getGoodsId())) {
//                            iTemp++;
//                        }
                    }
                }

                // 关联状态(all、none、part) default: none
                String relateStatus = "none";
                if (iTemp > 0) {
                    if (iTemp == item.getSkuList().size()) {
                        // 全部关联系统商品
                        relateStatus = "all";
                    } else {
                        // 部分关联系统商品
                        relateStatus = "part";
                    }

                    // 更新平台商品关联状态
                    cn.rkylin.oms.item.domain.Item itemUpdate = new Item();
                    itemUpdate.setEcItemCode(item.getEcItemCode());
                    itemUpdate.setShopId(shopId);
                    itemUpdate.setRelateStatus(relateStatus);
                    dao.update("updateByItemCodeSelectiveItem", itemUpdate);
                }
//                else {
//                    // 未关联系统商品
//                    relateStatus = "none";
//                }

//                // 更新平台商品关联状态
//                cn.rkylin.oms.item.domain.Item itemUpdate = new Item();
//                itemUpdate.setEcItemCode(item.getEcItemCode());
//                itemUpdate.setShopId(shopId);
//                itemUpdate.setRelateStatus(relateStatus);
//                dao.update("updateByItemCodeSelectiveItem", itemUpdate);
            }
        }
    }

    // 只用到shopId
    private void setShopProductsAmount(String shopId, ItemVO parameter) {
        // 缓存处理：如果没有缓存就重新算一下
        try {
            BoundValueOperations<Serializable, Serializable> ops = redisTemplate
                    .boundValueOps("shopProductAmount:" + shopId);
            String redisShopProductAmountData = ops.get(0, ops.size() - 1);
            if (StringUtils.isEmpty(redisShopProductAmountData)) {
                Integer shopProductAmount = (Integer) dao.find("selectItemCountByShipId", parameter);
                redisTemplate.opsForValue().append("shopProductAmount:" + shopId, shopProductAmount.toString());
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } // over
    }

    public void finalize() throws Throwable {
        super.finalize();
    }

}
